//   Copyright 2012,2013 Vaughn Vernon
//
//   Licensed under the Apache License, Version 2.0 (the "License");
//   you may not use this file except in compliance with the License.
//   You may obtain a copy of the License at
//
//       http://www.apache.org/licenses/LICENSE-2.0
//
//   Unless required by applicable law or agreed to in writing, software
//   distributed under the License is distributed on an "AS IS" BASIS,
//   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//   See the License for the specific language governing permissions and
//   limitations under the License.

package com.saasovation.common.domain.model;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.saasovation.common.AssertionConcern;

/**
 * 事件源根实体
 */
public abstract class EventSourcedRootEntity extends AssertionConcern {

    /**
     * 转换器方法名称
     */
    private static final String MUTATOR_METHOD_NAME = "when";
    /**
     * 变异器方法地图
     */
    private static Map<String, Method> mutatorMethods =
            new HashMap<String, Method>();
    /**
     * 突变事件清单
     */
    private List<DomainEvent> mutatingEvents;
    /**
     * 不变版本
     */
    private int unmutatedVersion;

    /**
     * 获取突变完版本
     * @return 返回整型
     */
    public int mutatedVersion() {
        return this.unmutatedVersion() + 1;
    }

    /**
     * 获取突变事件清单
     * @return  返回列表
     */
    public List<DomainEvent> mutatingEvents() {
        return this.mutatingEvents;
    }

    /**
     * 获取不变版本
     * @return 返回整型
     */
    public int unmutatedVersion() {
        return this.unmutatedVersion;
    }

    /**
     * 由以下参数构造事件源跟实体
     * @param anEventStream     事件流
     * @param aStreamVersion    流版本
     */
    protected EventSourcedRootEntity(
            List<DomainEvent> anEventStream,
            int aStreamVersion) {
        // 默认构造器
        this();
        // 遍历事件流,每一个领域事件进行处理
        for (DomainEvent event : anEventStream) {
            // 领域事件发生时，突变
            this.mutateWhen(event);
        }
        // 设置不变版本
        this.setUnmutatedVersion(aStreamVersion);
    }

    /**
     * 默认构造器：事件源根实体
     */
    protected EventSourcedRootEntity() {
        super();
        // 设置突变事件清单初始化
        this.setMutatingEvents(new ArrayList<DomainEvent>(2));
    }

    /**
     * 应用领域事件
     * @param aDomainEvent  领域事件
     */
    protected void apply(DomainEvent aDomainEvent) {

        // 追加领域事件到突变事件清单
        this.mutatingEvents().add(aDomainEvent);
        // 领域事件发生时，突变
        this.mutateWhen(aDomainEvent);
    }

    /**
     * 当（领域事件发生时），发生突变
     * @param aDomainEvent
     */
    protected void mutateWhen(DomainEvent aDomainEvent) {

        // 获取继承自：事件源根实体 的类
        Class<? extends EventSourcedRootEntity> rootType = this.getClass();
        // 从领域事件获取继承领域事件的类
        Class<? extends DomainEvent> eventType = aDomainEvent.getClass();
        // 定义根类型和事件类型 组成的键值
        String key = rootType.getName() + ":" + eventType.getName();

        // 从突变方法清单获取突变方法
        Method mutatorMethod = mutatorMethods.get(key);

        // 如果获取的突变方法为无效时，再从缓存里获取
        if (mutatorMethod == null) {
            mutatorMethod = this.cacheMutatorMethodFor(key, rootType, eventType);
        }

        try {
            // 执行方法
            mutatorMethod.invoke(this, aDomainEvent);

        } catch (InvocationTargetException e) {
            if (e.getCause() != null) {
                throw new RuntimeException(
                        "Method "
                                + MUTATOR_METHOD_NAME
                                + "("
                                + eventType.getSimpleName()
                                + ") failed. See cause: "
                                + e.getMessage(),
                        e.getCause());
            }

            throw new RuntimeException(
                    "Method "
                            + MUTATOR_METHOD_NAME
                            + "("
                            + eventType.getSimpleName()
                            + ") failed. See cause: "
                            + e.getMessage(),
                    e);

        } catch (IllegalAccessException e) {
            throw new RuntimeException(
                    "Method "
                            + MUTATOR_METHOD_NAME
                            + "("
                            + eventType.getSimpleName()
                            + ") failed because of illegal access. See cause: "
                            + e.getMessage(),
                    e);
        }
    }

    /**
     * 缓存突变器方法
     * @param aKey          键值
     * @param aRootType     根类型
     * @param anEventType   事件类型
     * @return              返回方法
     */
    private Method cacheMutatorMethodFor(
            String aKey,
            Class<? extends EventSourcedRootEntity> aRootType,
            Class<? extends DomainEvent> anEventType) {
        // 同步代码块
        synchronized (mutatorMethods) {
            try {
                Method method = this.hiddenOrPublicMethod(aRootType, anEventType);

                method.setAccessible(true);

                mutatorMethods.put(aKey, method);

                return method;

            } catch (Exception e) {
                throw new IllegalArgumentException(
                        "I do not understand "
                                + MUTATOR_METHOD_NAME
                                + "("
                                + anEventType.getSimpleName()
                                + ") because: "
                                + e.getClass().getSimpleName() + ">>>" + e.getMessage(),
                        e);
            }
        }
    }

    /**
     * 隐藏或公开方法
     * @param aRootType     根类型
     * @param anEventType   事件类型
     * @return              返回方法
     * @throws Exception
     */
    private Method hiddenOrPublicMethod(
            Class<? extends EventSourcedRootEntity> aRootType,
            Class<? extends DomainEvent> anEventType)
    throws Exception {

        // 建立一个无效的方法
        Method method = null;

        try {

            // assume protected or private...
            // 假定受保护或私有，取得方法
            method = aRootType.getDeclaredMethod(
                    MUTATOR_METHOD_NAME,
                    anEventType);

        } catch (Exception e) {

            // then public...
            // 如果上述发生异常的时候，再取得公开方法
            method = aRootType.getMethod(
                    MUTATOR_METHOD_NAME,
                    anEventType);
        }

        return method;
    }

    /**
     * 设置突变事件清单
     * @param aMutatingEventsList   突变事件清单
     */
    private void setMutatingEvents(List<DomainEvent> aMutatingEventsList) {
        this.mutatingEvents = aMutatingEventsList;
    }

    /**
     * 设置不变版本
     * @param aStreamVersion    流版本
     */
    private void setUnmutatedVersion(int aStreamVersion) {
        this.unmutatedVersion = aStreamVersion;
    }
}
